<?php
/**
 * Created by PhpStorm.
 * User: Tioncico
 * Date: 2019/3/29 0029
 * Time: 10:45
 */

namespace App\HttpController\Api;


use App\HttpController\BaseController;
use EasySwoole\EasySwoole\Core;
use EasySwoole\EasySwoole\Trigger;
use EasySwoole\Http\Exception\ParamAnnotationValidateError;
use EasySwoole\Http\Message\Status;
use EasySwoole\Jwt\Jwt;

abstract class ApiBase extends BaseController
{
    function index()
    {
        // TODO: Implement index() method.
        $this->actionNotFound('index');
    }

    protected function actionNotFound(?string $action): void
    {
        $this->writeJson(Status::CODE_NOT_FOUND);
    }

    function onRequest(?string $action): ?bool
    {
        if (!parent::onRequest($action)) {
            return false;
        };
        $token =  $this->request()->getRequestParam('token');
echo $action;
  /*      try {
            $jwtObject = Jwt::getInstance()->decode($token);

            $status = $jwtObject->getStatus();

            // 如果encode设置了秘钥,decode 的时候要指定
           //  $status = $jwt->setSecretKey('easyswoole')->decode($token)

            switch ($status)
            {
                case  1:
                    echo '验证通过';
                    $jwtObject->getAlg();
                    $jwtObject->getAud();
                    $jwtObject->getData();
                    $jwtObject->getExp();
                    $jwtObject->getIat();
                    $jwtObject->getIss();
                    $jwtObject->getNbf();
                    $jwtObject->getJti();
                    $jwtObject->getSub();
                    $jwtObject->getSignature();
                    $jwtObject->getProperty('alg');
                    break;
                case  -1:
                    echo '无效';
                    break;
                case  -2:
                    echo 'token过期';
                    break;
            }
        } catch (\EasySwoole\Jwt\Exception $e) {
            echo 'token可错误';
        }*/
        return true;
    }

    protected function onException(\Throwable $throwable): void
    {
        if ($throwable instanceof ParamAnnotationValidateError) {
            $msg = $throwable->getValidate()->getError()->getErrorRuleMsg();
            $this->writeJson(400, null, "{$msg}");
        } else {
            if (Core::getInstance()->isDev()) {
                $this->writeJson(500, null, $throwable->getMessage());
            } else {
                Trigger::getInstance()->throwable($throwable);
                $this->writeJson(500, null, '系统内部错误，请稍后重试');
            }
        }
    }
}